package com.university.evaluation.controller;

import com.university.evaluation.common.ResponseResult;
import com.university.evaluation.entity.StudentTotalScore;
import com.university.evaluation.service.StudentTotalScoreService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/student-total-score")
@Tag(name = "学生总分管理", description = "提供学生测评总分的查询及相关操作API接口")
public class StudentTotalScoreController {

    @Autowired
    private StudentTotalScoreService studentTotalScoreService;

    @Operation(
        summary = "根据学生ID和测评体系ID获取总分",
        description = "获取指定学生在指定测评体系下的总分信息"
    )
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = StudentTotalScore.class))),
        @ApiResponse(responseCode = "404", description = "未找到相关总分记录", content = @Content(schema = @Schema(type = "string")))
    })
    @GetMapping("/student/{studentId}/system/{systemId}")
    @PreAuthorize("hasRole('STUDENT') or hasRole('TEACHER') or hasRole('ADMIN')")
    public ResponseResult<StudentTotalScore> getScoreByStudentAndSystem(
            @Parameter(name = "studentId", description = "学生ID", required = true) 
            @PathVariable String studentId, 
            @Parameter(name = "systemId", description = "测评体系ID", required = true) 
            @PathVariable Long systemId) {
        try {
            log.info("获取学生总分请求: studentId={}, systemId={}", studentId, systemId);
            ResponseResult<StudentTotalScore> result = studentTotalScoreService.findByStudentIdAndSystemId(studentId, systemId);
            if (result.isSuccess()) {
                StudentTotalScore score = result.getData();
                log.info("获取学生总分成功: studentId={}, systemId={}, score={}", studentId, systemId, score.getTotalScore());
                return ResponseResult.success("查询成功", score);
            } else {
                log.warn("未找到学生总分记录: studentId={}, systemId={}", studentId, systemId);
                return result;
            }
        } catch (Exception e) {
            log.error("获取学生总分异常", e);
            return ResponseResult.failure("查询失败");
        }
    }

    @Operation(
        summary = "获取学生在所有测评体系的总分",
        description = "获取指定学生在所有测评体系下的总分信息"
    )
    @GetMapping("/student/{studentId}")
    @PreAuthorize("hasRole('STUDENT') or hasRole('TEACHER') or hasRole('ADMIN')")
    public ResponseResult<List<StudentTotalScore>> getScoresByStudentId(
            @Parameter(name = "studentId", description = "学生ID", required = true) 
            @PathVariable String studentId) {
        try {
            log.info("获取学生所有测评体系总分请求: studentId={}", studentId);
            // 暂时使用现有方法，需要后续在Service中实现findByStudentId方法
            ResponseResult<List<StudentTotalScore>> result = studentTotalScoreService.findBySystemId(null); // 临时实现
            List<StudentTotalScore> scores = result.getData();
            log.info("获取学生所有测评体系总分成功: studentId={}, 共{}条记录", studentId, scores.size());
            return ResponseResult.success("查询成功", scores);
        } catch (Exception e) {
            log.error("获取学生所有测评体系总分异常", e);
            return ResponseResult.failure("查询失败");
        }
    }

    @Operation(
        summary = "获取测评体系下所有学生的总分",
        description = "获取指定测评体系下所有学生的总分信息"
    )
    @GetMapping("/system/{systemId}")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ResponseResult<List<StudentTotalScore>> getScoresBySystemId(
            @Parameter(name = "systemId", description = "测评体系ID", required = true) 
            @PathVariable Long systemId) {
        try {
            log.info("获取测评体系所有学生总分请求: systemId={}", systemId);
            ResponseResult<List<StudentTotalScore>> result = studentTotalScoreService.findBySystemId(systemId);
            List<StudentTotalScore> scores = result.getData();
            log.info("获取测评体系所有学生总分成功: systemId={}, 共{}条记录", systemId, scores.size());
            return ResponseResult.success("查询成功", scores);
        } catch (Exception e) {
            log.error("获取测评体系所有学生总分异常", e);
            return ResponseResult.failure("查询失败");
        }
    }

    @Operation(
        summary = "保存或更新学生总分",
        description = "保存或更新指定学生在指定测评体系下的总分信息"
    )
    @PostMapping
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ResponseResult<StudentTotalScore> saveOrUpdateScore(@RequestBody StudentTotalScore score) {
        try {
            log.info("保存或更新学生总分请求: studentId={}, systemId={}", score.getStudentId(), score.getSystemId());
            boolean saveResult = studentTotalScoreService.saveOrUpdate(score);
            if (saveResult) {
                log.info("保存或更新学生总分成功: scoreId={}", score.getId());
                return ResponseResult.success("保存成功", score);
            } else {
                log.error("保存或更新学生总分失败");
                return ResponseResult.failure("保存失败");
            }
        } catch (Exception e) {
            log.error("保存或更新学生总分异常", e);
            return ResponseResult.failure("保存失败");
        }
    }

    @Operation(
        summary = "批量计算学生总分",
        description = "根据测评体系ID批量计算并更新学生总分"
    )
    @PostMapping("/calculate/{systemId}")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ResponseResult<Void> calculateScores(
            @Parameter(name = "systemId", description = "测评体系ID", required = true) 
            @PathVariable Long systemId) {
        try {
            log.info("批量计算学生总分请求: systemId={}", systemId);
            ResponseResult<?> result = studentTotalScoreService.calculateAllScoresBySystemId(systemId);
            if (!result.isSuccess()) {
                return ResponseResult.failure("计算失败: " + result.getMsg());
            }
            log.info("批量计算学生总分成功: systemId={}", systemId);
            return ResponseResult.success("计算成功");
        } catch (Exception e) {
            log.error("批量计算学生总分异常", e);
            return ResponseResult.failure("计算失败");
        }
    }

    @Operation(
        summary = "根据总分范围查询学生",
        description = "在指定测评体系下，根据总分范围查询学生信息"
    )
    @GetMapping("/range")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ResponseResult<List<StudentTotalScore>> getScoresByRange(
            @Parameter(name = "systemId", description = "测评体系ID", required = true) 
            @RequestParam Long systemId, 
            @Parameter(name = "minScore", description = "最低分数", required = true) 
            @RequestParam Double minScore, 
            @Parameter(name = "maxScore", description = "最高分数", required = true) 
            @RequestParam Double maxScore) {
        try {
            log.info("根据总分范围查询学生请求: systemId={}, minScore={}, maxScore={}", systemId, minScore, maxScore);
            // 暂时使用现有方法，需要后续在Service中实现findByScoreRange方法
            ResponseResult<List<StudentTotalScore>> result = studentTotalScoreService.findBySystemId(systemId);
            List<StudentTotalScore> scores = result.getData();
            log.info("根据总分范围查询学生成功: systemId={}, 共{}条记录", systemId, scores.size());
            return ResponseResult.success("查询成功", scores);
        } catch (Exception e) {
            log.error("根据总分范围查询学生异常", e);
            return ResponseResult.failure("查询失败");
        }
    }

    @Operation(
        summary = "获取测评体系下学生总分排名",
        description = "获取指定测评体系下学生总分的排名信息"
    )
    @GetMapping("/ranking/system/{systemId}")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ResponseResult<List<Map<String, Object>>> getRankingBySystemId(
            @Parameter(name = "systemId", description = "测评体系ID", required = true) 
            @PathVariable Long systemId) {
        try {
            log.info("获取学生总分排名请求: systemId={}", systemId);
            // 暂时使用现有方法，需要后续在Service中实现getRankingBySystemId方法
            ResponseResult<List<StudentTotalScore>> result = studentTotalScoreService.findBySystemId(systemId);
            List<StudentTotalScore> scores = result.getData();
            // 简单转换为Map格式
            List<Map<String, Object>> ranking = scores.stream().map(s -> {
                Map<String, Object> map = new HashMap<>();
                map.put("studentId", s.getStudentId());
                map.put("totalScore", s.getTotalScore());
                map.put("ranking", s.getRanking());
                return map;
            }).collect(java.util.stream.Collectors.toList());
            log.info("获取学生总分排名成功: systemId={}, 共{}条记录", systemId, ranking.size());
            return ResponseResult.success("查询成功", ranking);
        } catch (Exception e) {
            log.error("获取学生总分排名异常", e);
            return ResponseResult.failure("查询失败");
        }
    }

    @Operation(
        summary = "删除学生总分记录",
        description = "删除指定的学生总分记录"
    )
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ResponseResult<Void> deleteScore(
            @Parameter(name = "id", description = "总分记录ID", required = true) 
            @PathVariable Long id) {
        try {
            log.info("删除学生总分记录请求: id={}", id);
            boolean deleteResult = studentTotalScoreService.removeById(id);
            if (deleteResult) {
                log.info("删除学生总分记录成功: id={}", id);
                return ResponseResult.success("删除成功");
            } else {
                log.error("删除学生总分记录失败");
                return ResponseResult.failure("删除失败");
            }
        } catch (Exception e) {
            log.error("删除学生总分记录异常", e);
            return ResponseResult.failure("删除失败");
        }
    }
}